// 用户账号管理模块
class UserManagementManager {
    static loadContent(container) {
        container.innerHTML = `
            <div class="description">
                管理系统用户账号，包括创建、修改、删除用户账号，以及设置用户所属角色和部门。
            </div>
            
            <div class="actions">
                <button class="btn-primary btn-add-user"><i class="fas fa-plus"></i> 新增用户</button>
                <button class="btn btn-batch-import"><i class="fas fa-file-import"></i> 批量导入</button>
                <button class="btn btn-export-user"><i class="fas fa-file-export"></i> 导出用户</button>
                <button class="btn btn-delete-user"><i class="fas fa-trash"></i> 删除用户</button>
                <div class="search-area">
                    <input type="text" id="search-user-input" placeholder="搜索账号...">
                    <input type="text" id="search-phone-input" placeholder="搜索手机号...">
                    <button id="search-btn" class="btn-primary"><i class="fas fa-search"></i> 搜索</button>
                </div>
            </div>
            
            <div class="table-container">
                <table>
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="selectAllUsers"></th>
                            <th>账号</th>
                            <th>用户名称</th>
                            <th>部门</th>
                            <th>角色</th>
                            <th>手机号码</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>admin</td>
                            <td>系统管理员</td>
                            <td>总部</td>
                            <td>管理员</td>
                            <td>15217895411</td>
                            <td><button class="status-btn active">正常</button></td>
                            <td>2023-10-01 08:30:00</td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>teacher01</td>
                            <td>张老师</td>
                            <td>总部</td>
                            <td>教师</td>
                            <td>13914565866</td>
                            <td><button class="status-btn active">正常</button></td>
                            <td>2023-10-05 14:20:00</td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                        <tr>
                            <td><input type="checkbox" class="rowCheckbox"></td>
                            <td>student01</td>
                            <td>李同学</td>
                            <td>计算机学院</td>
                            <td>学员</td>
                            <td>18245129876</td>
                            <td><button class="status-btn active">正常</button></td>
                            <td>2023-10-10 09:15:00</td>
                            <td class="operation">
                                <a href="#"><i class="fas fa-edit"></i> 编辑</a>
                                <a href="#"><i class="fas fa-trash"></i> 删除</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div class="pagination">
                <a href="#">上一页</a>
                <a href="#" class="active">1</a>
                <a href="#">2</a>
                <a href="#">3</a>
                <a href="#">4</a>
                <a href="#">5</a>
                <a href="#">下一页</a>
            </div>
        `;
        
        // 设置全选功能
        mainManager.setupSelectAll('selectAllUsers', 'rowCheckbox');
        
        // 设置操作按钮事件
        systemManager.setupActionButtons(container);
        
        // 绑定新增用户按钮事件
        const addUserBtn = container.querySelector('.btn-add-user');
        if (addUserBtn) {
            addUserBtn.addEventListener('click', AddUserModal.showModal);
        }

        // 绑定批量导入按钮事件
        const batchImportBtn = container.querySelector('.btn-batch-import');
        if (batchImportBtn) {
            batchImportBtn.addEventListener('click', BatchImportModal.showModal);
        }

        // 设置搜索功能
        const searchBtn = container.querySelector('#search-btn');
        const searchUserInput = container.querySelector('#search-user-input');
        const searchPhoneInput = container.querySelector('#search-phone-input');

        // 执行搜索的函数
        const executeSearch = () => {
            const userKeyword = searchUserInput.value.trim();
            const phoneKeyword = searchPhoneInput.value.trim();

            // 如果两个搜索框都为空，提示用户
            if (!userKeyword && !phoneKeyword) {
                alert('请输入搜索条件');
                return;
            }

            UserManagementManager.performCombinedSearch(userKeyword, phoneKeyword, container);
        };

        // 搜索按钮点击事件
        if (searchBtn) {
            searchBtn.addEventListener('click', executeSearch);
        }

        // 两个输入框支持回车搜索
        if (searchUserInput) {
            searchUserInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    executeSearch();
                }
            });
        }

        if (searchPhoneInput) {
            searchPhoneInput.addEventListener('keypress', (e) => {
                if (e.key === 'Enter') {
                    executeSearch();
                }
            });
        }

        // 注册组织架构数据变化事件监听
        OrgStructureManager.onOrgDataChange(() => {
            // 如果新增用户模态框已打开，需要重新加载部门列表
            if (AddUserModal.isModalOpen()) {
                AddUserModal.loadDepartments();
            }
        });
        
        // 为编辑按钮添加点击事件（使用事件委托）
        const tableBody = container.querySelector('.table-container tbody');
        if (tableBody) {
            tableBody.addEventListener('click', (e) => {
                // 检查点击的是否是编辑按钮
                const editButton = e.target.closest('.operation a:first-child');
                if (editButton) {
                    e.preventDefault();
                    // 获取当前行的用户数据
                    const row = editButton.closest('tr');
                    if (row) {
                        const userData = {
                            id: row.rowIndex, // 实际项目中应从数据中获取
                            account: row.cells[1].textContent,
                            username: row.cells[2].textContent,
                            department: row.cells[3].textContent,
                            role: row.cells[4].textContent,
                            phone: row.cells[5].textContent
                        };
                        EditUserModal.showModal(userData);
                    }
                }
            });
        }
    }

    // 执行组合搜索功能
    static performCombinedSearch(userKeyword, phoneKeyword, container) {
        const tableBody = container.querySelector('.table-container tbody');
        if (!tableBody) return;

        const rows = tableBody.querySelectorAll('tr');
        let foundCount = 0;

        rows.forEach(row => {
            let matchFound = true; // 默认匹配

            // 如果用户账号搜索框有内容，检查是否匹配
            if (userKeyword) {
                const keywordLower = userKeyword.toLowerCase();
                const accountCell = row.cells[1];
                const usernameCell = row.cells[2];

                let userMatch = false;
                if (accountCell && usernameCell) {
                    const accountText = accountCell.textContent.toLowerCase();
                    const usernameText = usernameCell.textContent.toLowerCase();
                    userMatch = accountText.includes(keywordLower) || usernameText.includes(keywordLower);
                }

                matchFound = matchFound && userMatch;
            }

            // 如果手机号搜索框有内容，检查是否匹配
            if (phoneKeyword) {
                const keywordLower = phoneKeyword.toLowerCase();
                const phoneCell = row.cells[5];

                let phoneMatch = false;
                if (phoneCell) {
                    const phoneText = phoneCell.textContent.toLowerCase();
                    phoneMatch = phoneText.includes(keywordLower);
                }

                matchFound = matchFound && phoneMatch;
            }

            // 显示或隐藏行
            if (matchFound) {
                row.style.display = '';
                foundCount++;
            } else {
                row.style.display = 'none';
            }
        });

        // 显示搜索结果提示
        if (foundCount === 0) {
            alert('未找到匹配的记录');
        } else {
            console.log(`找到 ${foundCount} 条匹配记录`);
        }
    }
}

// 新增用户模态框实现
class AddUserModal {
    static showModal() {
        // 创建模态框元素
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'addUserModal';
        
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>新增用户</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="add-user-form">
                    <div class="form-group">
                        <label for="account">账号</label>
                        <input type="text" id="account" name="account" class="form-control" placeholder="字母、数字、6-20个字符" required>
                        <div class="error-text" id="account-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="username">用户名称</label>
                        <input type="text" id="username" name="username" class="form-control" placeholder="2-10个字符" required>
                        <div class="error-text" id="username-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="phone">手机号</label>
                        <input type="tel" id="phone" name="phone" class="form-control" placeholder="11位数字" required>
                        <div class="error-text" id="phone-error"></div>
                    </div>
                    <div class="form-group">
                        <label id="add-status-label">用户状态</label>
                        <div class="custom-radio-group" role="radiogroup" aria-labelledby="add-status-label" style="display: flex; gap: 20px;">
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="add-status-normal" name="add-status" value="1" checked>
                                <label for="add-status-normal" style="margin-bottom: 0; margin-left: 8px;">正常</label>
                            </div>
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="add-status-disabled" name="add-status" value="0">
                                <label for="add-status-disabled" style="margin-bottom: 0; margin-left: 8px;">停用</label>
                            </div>
                        </div>
                        <div class="error-text" id="add-status-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="department">部门</label>
                        <select id="department" name="department" class="form-control" required>
                            <option value="">请选择部门</option>
                            <!-- 动态加载部门数据 -->
                        </select>
                        <div class="error-text" id="department-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="roles">角色</label>
                        <div class="custom-multiselect">
                            <div class="multiselect-header" id="roles-multiselect-header">
                                <input type="text" placeholder="选择角色" class="multiselect-input" readonly>
                                <button type="button" class="multiselect-toggle-btn"><i class="fas fa-chevron-down"></i></button>
                            </div>
                            <div class="multiselect-dropdown" id="roles-multiselect-dropdown">
                                <div class="multiselect-search">
                                    <input type="text" placeholder="搜索角色" id="roles-search-input">
                                </div>
                                <div class="multiselect-options" id="roles-multiselect-options"></div>
                            </div>
                            <select id="roles" name="roles" class="form-control d-none" multiple required></select>
                        </div>
                        <div class="error-text" id="roles-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="password">密码</label>
                        <div class="password-container">
                            <input type="password" id="password" name="password" class="form-control" placeholder="8-20个字符，至少三种类型" required>
                            <button type="button" class="password-toggle-btn" id="toggle-password"><i class="fas fa-eye"></i></button>
                        </div>
                        <div class="password-strength" id="password-strength"></div>
                        <div class="error-text" id="password-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="confirmPassword">确认密码</label>
                        <div class="password-container">
                            <input type="password" id="confirmPassword" name="confirmPassword" class="form-control" placeholder="与密码一致" required>
                            <button type="button" class="password-toggle-btn" id="toggle-confirm-password"><i class="fas fa-eye"></i></button>
                        </div>
                        <div class="error-text" id="confirmPassword-error"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="save-btn" disabled>保存</button>
                    </div>
                </form>
            </div>
        `;
        
        // 添加到文档
        document.body.appendChild(modal);
        
        // 初始化事件
        AddUserModal.initEvents();
        
        // 加载部门数据
        AddUserModal.loadDepartments();
        
        // 加载角色数据
        AddUserModal.loadRoles();
        
        // 显示模态框
        modal.classList.add('show');
    }
    
    static initEvents() {
        const modal = document.getElementById('addUserModal');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = document.getElementById('cancel-btn');
        const saveBtn = document.getElementById('save-btn');
        const form = modal.querySelector('.add-user-form');
        
        // 关闭事件
        closeBtn.addEventListener('click', AddUserModal.closeModal);
        cancelBtn.addEventListener('click', AddUserModal.closeModal);
        
        // 点击外部关闭
        modal.querySelector('.modal-overlay').addEventListener('click', AddUserModal.closeModal);
        
        // ESC键关闭
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('show')) {
                AddUserModal.closeModal();
            }
        });
        
        // 密码可见性切换
        document.getElementById('toggle-password').addEventListener('click', function() {
            const passwordInput = document.getElementById('password');
            const type = passwordInput.type === 'password' ? 'text' : 'password';
            passwordInput.type = type;
            this.querySelector('i').classList.toggle('fa-eye');
            this.querySelector('i').classList.toggle('fa-eye-slash');
        });
        
        document.getElementById('toggle-confirm-password').addEventListener('click', function() {
            const passwordInput = document.getElementById('confirmPassword');
            const type = passwordInput.type === 'password' ? 'text' : 'password';
            passwordInput.type = type;
            this.querySelector('i').classList.toggle('fa-eye');
            this.querySelector('i').classList.toggle('fa-eye-slash');
        });
        
        // 表单验证
        AddUserModal.initFormValidation(form);
        
        // 表单提交
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            AddUserModal.submitForm(form);
        });

        // 为状态单选框组添加键盘导航支持
        const radioGroup = modal.querySelector('.custom-radio-group');
        if (radioGroup) {
            const radioButtons = radioGroup.querySelectorAll('input[type="radio"]');

            // 添加键盘事件处理
            radioGroup.addEventListener('keydown', (e) => {
                const currentIndex = Array.from(radioButtons).findIndex(radio => radio === document.activeElement);

                if (currentIndex !== -1) {
                    // 右箭头或下箭头：选择下一个选项
                    if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
                        e.preventDefault();
                        const nextIndex = (currentIndex + 1) % radioButtons.length;
                        radioButtons[nextIndex].focus();
                        radioButtons[nextIndex].checked = true;
                    }
                    // 左箭头或上箭头：选择上一个选项
                    else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
                        e.preventDefault();
                        const prevIndex = (currentIndex - 1 + radioButtons.length) % radioButtons.length;
                        radioButtons[prevIndex].focus();
                        radioButtons[prevIndex].checked = true;
                    }
                    // 空格键：切换选中状态
                    else if (e.key === ' ') {
                        e.preventDefault();
                        radioButtons[currentIndex].checked = true;
                    }
                }
            });

            // 添加焦点状态样式支持
            radioButtons.forEach(radio => {
                radio.addEventListener('focus', () => {
                    radio.parentElement.classList.add('focused');
                });

                radio.addEventListener('blur', () => {
                    radio.parentElement.classList.remove('focused');
                });
            });
        }
    }
    
    // 加载部门数据
    static loadDepartments() {
        const departmentSelect = document.getElementById('department');
        const errorElement = document.getElementById('department-error');
        
        // 清空现有选项
        departmentSelect.innerHTML = '<option value="">加载中...</option>';
        errorElement.textContent = '';
        
        try {
            // 从组织架构管理模块获取所有组织数据
            const organizations = OrgStructureManager.getAllOrganizations();
            
            // 清空并重新构建选项
            departmentSelect.innerHTML = '<option value="">请选择部门</option>';
            
            // 按层级顺序显示组织
            const sortedOrgs = organizations.sort((a, b) => {
                // 按parentId和id排序，确保层级关系正确
                if (a.parentId === b.parentId) {
                    return a.id - b.id;
                }
                return a.parentId - b.parentId;
            });
            
            // 添加选项
            sortedOrgs.forEach(org => {
                const option = document.createElement('option');
                option.value = org.id;
                
                // 根据层级添加缩进
                let indent = '';
                let currentOrg = org;
                while (currentOrg.parentId !== 0) {
                    indent += '    ';
                    currentOrg = organizations.find(o => o.id === currentOrg.parentId);
                }
                
                option.textContent = indent + org.name;
                option.dataset.code = org.code;
                option.dataset.type = org.type;
                
                departmentSelect.appendChild(option);
            });
        } catch (error) {
            console.error('加载部门数据失败:', error);
            departmentSelect.innerHTML = '<option value="">加载失败</option>';
            errorElement.textContent = '加载部门数据失败，请稍后重试';
        }
    }
    
    // 加载角色数据
    static loadRoles() {
        const multiselectOptions = document.getElementById('roles-multiselect-options');
        const rolesSelect = document.getElementById('roles');
        const errorElement = document.getElementById('roles-error');
        
        // 清空现有选项
        multiselectOptions.innerHTML = '<div class="multiselect-option"><span>加载中...</span></div>';
        errorElement.textContent = '';
        
        try {
            // 从用户角色管理模块获取所有角色数据
            const roles = UserRoleManager.getAllRoles();
            
            // 清空并重新构建选项
            multiselectOptions.innerHTML = '';
            rolesSelect.innerHTML = '';
            
            // 按ID排序角色
            const sortedRoles = roles.sort((a, b) => a.id - b.id);
            
            // 添加选项到自定义多选组件和隐藏的原生select
            sortedRoles.forEach(role => {
                // 自定义多选组件的选项
                const optionDiv = document.createElement('div');
                optionDiv.className = 'multiselect-option';
                optionDiv.dataset.roleId = role.id;
                
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.value = role.id;
                checkbox.id = `role-checkbox-${role.id}`;
                
                const label = document.createElement('label');
                label.htmlFor = `role-checkbox-${role.id}`;
                label.textContent = role.name;
                label.dataset.roleId = role.id;
                
                optionDiv.appendChild(checkbox);
                optionDiv.appendChild(label);
                multiselectOptions.appendChild(optionDiv);
                
                // 原生select的选项（用于表单提交）
                const option = document.createElement('option');
                option.value = role.id;
                option.textContent = role.name;
                option.dataset.code = role.code;
                rolesSelect.appendChild(option);
            });
            
            // 初始化自定义多选组件的事件
            AddUserModal.initCustomMultiselect();
        } catch (error) {
            console.error('加载角色数据失败:', error);
            multiselectOptions.innerHTML = '<div class="multiselect-option"><span>加载失败</span></div>';
            errorElement.textContent = '角色数据加载失败，请稍后重试。';
        }
    }
    
    static initFormValidation(form) {
        // 动态表单验证逻辑
        const fields = ['account', 'username', 'phone', 'password', 'confirmPassword'];
        
        fields.forEach(field => {
            const input = form[field];
            input.addEventListener('input', () => {
                AddUserModal.validateField(field, input.value);
                AddUserModal.checkFormValidity(form);
            });
        });
        
        // 角色选择验证
        const rolesSelect = document.getElementById('roles');
        rolesSelect.addEventListener('change', () => {
            AddUserModal.validateField('roles', Array.from(rolesSelect.selectedOptions).map(option => option.value));
            AddUserModal.checkFormValidity(form);
        });
        
        // 部门选择验证
        const departmentSelect = document.getElementById('department');
        departmentSelect.addEventListener('change', () => {
            AddUserModal.validateField('department', departmentSelect.value);
            AddUserModal.checkFormValidity(form);
        });
    }
    
    static validateField(field, value) {
        let isValid = true;
        let errorMessage = '';
        
        switch (field) {
            case 'account':
                const accountRegex = /^[a-zA-Z0-9_]{6,20}$/;
                if (!value) {
                    errorMessage = '账号不能为空';
                    isValid = false;
                } else if (!accountRegex.test(value)) {
                    errorMessage = '账号只能包含字母、数字和，长度6-20个字符';
                    isValid = false;
                }
                break;
            
            case 'username':
                if (!value) {
                    errorMessage = '用户名称不能为空';
                    isValid = false;
                } else if (value.length < 2 || value.length > 10) {
                    errorMessage = '用户名称长度为2-10个字符';
                    isValid = false;
                }
                break;
            
            case 'phone':
                const phoneRegex = /^1[3-9]\d{9}$/;
                if (!value) {
                    errorMessage = '手机号不能为空';
                    isValid = false;
                } else if (!phoneRegex.test(value)) {
                    errorMessage = '请输入有效的11位手机号';
                    isValid = false;
                }
                break;
            
            case 'department':
                if (!value) {
                    errorMessage = '请选择部门';
                    isValid = false;
                }
                break;
            
            case 'roles':
                if (!value || value.length === 0) {
                    errorMessage = '至少选择一个角色';
                    isValid = false;
                }
                break;
            
            case 'password':
                const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,20}$/;
                const passwordRegex2 = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,20}$/;
                const passwordRegex3 = /^(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,20}$/;
                const passwordRegex4 = /^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,20}$/;
                
                if (!value) {
                    errorMessage = '密码不能为空';
                    isValid = false;
                } else if (value.length < 8 || value.length > 20) {
                    errorMessage = '密码长度为8-20个字符';
                    isValid = false;
                } else if (!(passwordRegex.test(value) || passwordRegex2.test(value) || passwordRegex3.test(value) || passwordRegex4.test(value))) {
                    errorMessage = '密码至少包含大小写字母、数字和特殊符号中的三种';
                    isValid = false;
                }
                // 更新密码强度显示
                AddUserModal.updatePasswordStrength(value);
                break;
            
            case 'confirmPassword':
                const password = document.getElementById('password').value;
                if (!value) {
                    errorMessage = '请确认密码';
                    isValid = false;
                } else if (value !== password) {
                    errorMessage = '两次密码输入不一致';
                    isValid = false;
                }
                break;
        }
        
        // 更新错误信息
        const errorElement = document.getElementById(`${field}-error`);
        if (errorElement) {
            errorElement.textContent = errorMessage;
            errorElement.style.display = errorMessage ? 'block' : 'none';
        }
        
        // 添加验证状态类
        const inputElement = document.getElementById(field) || document.getElementById(field + 'Select');
        if (inputElement) {
            if (isValid) {
                inputElement.classList.remove('is-invalid');
                inputElement.classList.add('is-valid');
            } else {
                inputElement.classList.remove('is-valid');
                inputElement.classList.add('is-invalid');
            }
        }
        
        return isValid;
    }
    
    static updatePasswordStrength(password) {
        const strengthElement = document.getElementById('password-strength');
        if (!strengthElement) return;
        
        let strength = '弱';
        let strengthClass = 'weak';
        
        if (password.length > 0) {
            if (password.length < 8) {
                strength = '太短';
                strengthClass = 'short';
            } else if (/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{12,}$/.test(password)) {
                strength = '强';
                strengthClass = 'strong';
            } else if ((/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$/.test(password) || 
                        /^(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,}$/.test(password) || 
                        /^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]).{8,}$/.test(password)) && password.length >= 10) {
                strength = '中';
                strengthClass = 'medium';
            }
        } else {
            strength = '';
            strengthClass = '';
        }
        
        strengthElement.textContent = `密码强度: ${strength}`;
        strengthElement.className = `password-strength ${strengthClass}`;
        strengthElement.style.display = password ? 'block' : 'none';
    }
    
    static checkFormValidity(form) {
        const saveBtn = document.getElementById('save-btn');
        let isFormValid = true;
        
        // 验证所有必填字段
        const requiredFields = ['account', 'username', 'phone', 'department', 'password', 'confirmPassword'];
        
        for (const field of requiredFields) {
            const input = form[field];
            const isValid = AddUserModal.validateField(field, input.value);
            if (!isValid) {
                isFormValid = false;
            }
        }
        
        // 验证角色选择
        const rolesSelect = document.getElementById('roles');
        const rolesValid = AddUserModal.validateField('roles', Array.from(rolesSelect.selectedOptions).map(option => option.value));
        if (!rolesValid) {
            isFormValid = false;
        }
        
        // 更新保存按钮状态
        saveBtn.disabled = !isFormValid;
    }
    
    static submitForm(form) {
        // 表单提交逻辑
        const saveBtn = document.getElementById('save-btn');
        const originalText = saveBtn.textContent;
        
        // 显示加载状态
        saveBtn.textContent = '保存中...';
        saveBtn.disabled = true;
        
        // 收集表单数据
        const formData = {
            account: form.account.value,
            username: form.username.value,
            phone: form.phone.value,
            department: form.department.value,
            roles: Array.from(document.getElementById('roles').selectedOptions).map(option => option.value),
            password: form.password.value,
            confirmPassword: form.confirmPassword.value,
            status: document.querySelector('input[name="add-status"]:checked').value
        };
        
        // 模拟API请求
        setTimeout(() => {
            // 模拟API响应
            const success = true;
            
            if (success) {
                // 成功处理
                alert('新增用户成功');
                AddUserModal.closeModal();
                // 刷新用户列表
                const contentContainer = document.querySelector('.content');
                UserManagementManager.loadContent(contentContainer);
            } else {
                // 失败处理
                alert('新增用户失败，请重试');
            }
            
            // 恢复按钮状态
            saveBtn.textContent = originalText;
            saveBtn.disabled = false;
        }, 1500);
    }
    
    static closeModal() {
        const modal = document.getElementById('addUserModal');
        if (modal) {
            modal.classList.remove('show');
            // 移除模态框
            setTimeout(() => {
                modal.remove();
            }, 300);
        }
    }
    
    // 初始化自定义多选组件
    static initCustomMultiselect() {
        const multiselect = document.querySelector('.custom-multiselect');
        const header = document.getElementById('roles-multiselect-header');
        const dropdown = document.getElementById('roles-multiselect-dropdown');
        const optionsContainer = document.getElementById('roles-multiselect-options');
        const searchInput = document.getElementById('roles-search-input');
        const hiddenSelect = document.getElementById('roles');
        const inputDisplay = multiselect.querySelector('.multiselect-input');
        
        // 切换下拉框
        header.addEventListener('click', (e) => {
            // 避免点击输入框时关闭下拉框
            if (!e.target.closest('.multiselect-input')) {
                multiselect.classList.toggle('open');
            }
        });
        
        // 选择/取消选择选项
        optionsContainer.addEventListener('click', (e) => {
            const optionDiv = e.target.closest('.multiselect-option');
            if (optionDiv) {
                const checkbox = optionDiv.querySelector('input[type="checkbox"]');
                if (checkbox) {
                    checkbox.checked = !checkbox.checked;
                    optionDiv.classList.toggle('selected', checkbox.checked);
                    
                    // 更新原生select元素
                    const option = hiddenSelect.querySelector(`option[value="${checkbox.value}"]`);
                    if (option) {
                        option.selected = checkbox.checked;
                    }
                    
                    // 更新显示的文本
                    AddUserModal.updateMultiselectDisplay();
                    
                    // 触发验证
                    AddUserModal.validateField('roles', Array.from(hiddenSelect.selectedOptions).map(opt => opt.value));
                    AddUserModal.checkFormValidity(document.getElementById('addUserModalForm'));
                }
            }
        });
        
        // 搜索功能
        searchInput.addEventListener('input', (e) => {
            const searchText = e.target.value.toLowerCase();
            const options = optionsContainer.querySelectorAll('.multiselect-option');
            
            options.forEach(option => {
                const label = option.querySelector('label');
                const roleName = label.textContent.toLowerCase();
                
                if (roleName.includes(searchText)) {
                    option.style.display = 'flex';
                } else {
                    option.style.display = 'none';
                }
            });
        });
        
        // 点击外部关闭下拉框
        document.addEventListener('click', (e) => {
            if (!multiselect.contains(e.target)) {
                multiselect.classList.remove('open');
            }
        });
    }
    
    // 更新多选组件的显示文本
    static updateMultiselectDisplay() {
        const hiddenSelect = document.getElementById('roles');
        const inputDisplay = document.querySelector('.custom-multiselect .multiselect-input');
        const selectedOptions = Array.from(hiddenSelect.selectedOptions);
        
        if (selectedOptions.length === 0) {
            inputDisplay.placeholder = '选择角色';
            inputDisplay.value = '';
        } else if (selectedOptions.length === 1) {
            inputDisplay.value = selectedOptions[0].textContent;
        } else {
            inputDisplay.value = `${selectedOptions.length}个角色已选择`;
        }
    }
    
    // 检查模态框是否打开
    static isModalOpen() {
        const modal = document.getElementById('addUserModal');
        return modal !== null && modal.classList.contains('show');
    }
}

// 修改用户模态框实现
class EditUserModal {
    // 显示修改用户模态框
    static showModal(userData) {
        // 创建模态框元素
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'editUserModal';
        modal.dataset.userId = userData.id;
        
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h3>修改用户</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <form class="edit-user-form">
                    <input type="hidden" id="edit-user-id" value="${userData.id}">
                    <div class="form-group">
                        <label for="edit-account">账号</label>
                        <input type="text" id="edit-account" name="account" class="form-control" value="${userData.account}" disabled>
                    </div>
                    <div class="form-group">
                        <label for="edit-username">用户名称</label>
                        <input type="text" id="edit-username" name="username" class="form-control" value="${userData.username}" placeholder="2-10个字符" required>
                        <div class="error-text" id="edit-username-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-phone">手机号</label>
                        <input type="tel" id="edit-phone" name="phone" class="form-control" value="${userData.phone}" placeholder="11位数字" required>
                        <div class="error-text" id="edit-phone-error"></div>
                    </div>
                    <div class="form-group">
                        <label id="status-label">用户状态</label>
                        <div class="custom-radio-group" role="radiogroup" aria-labelledby="status-label" style="display: flex; gap: 20px;">
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="status-normal" name="status" value="1" checked>
                                <label for="status-normal" style="margin-bottom: 0; margin-left: 8px;">正常</label>
                            </div>
                            <div class="radio-option" style="display: flex; align-items: center;">
                                <input type="radio" id="status-disabled" name="status" value="0">
                                <label for="status-disabled" style="margin-bottom: 0; margin-left: 8px;">停用</label>
                            </div>
                        </div>
                        <div class="error-text" id="edit-status-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-department">部门</label>
                        <select id="edit-department" name="department" class="form-control" required>
                            <option value="">加载中...</option>
                        </select>
                        <div class="error-text" id="edit-department-error"></div>
                    </div>
                    <div class="form-group">
                        <label for="edit-roles">角色</label>
                        <div class="custom-multiselect">
                            <div class="multiselect-header" id="edit-roles-multiselect-header">
                                <input type="text" placeholder="选择角色" class="multiselect-input" readonly>
                                <button type="button" class="multiselect-toggle-btn"><i class="fas fa-chevron-down"></i></button>
                            </div>
                            <div class="multiselect-dropdown" id="edit-roles-multiselect-dropdown">
                                <div class="multiselect-search">
                                    <input type="text" placeholder="搜索角色" id="edit-roles-search-input">
                                </div>
                                <div class="multiselect-options" id="edit-roles-multiselect-options"></div>
                            </div>
                            <select id="edit-roles" name="roles" class="form-control d-none" multiple required></select>
                        </div>
                        <div class="error-text" id="edit-roles-error"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" id="edit-cancel-btn">取消</button>
                        <button type="submit" class="btn btn-primary" id="edit-save-btn" disabled>保存</button>
                    </div>
                </form>
            </div>
        `;
        
        // 添加到文档
        document.body.appendChild(modal);
        
        // 初始化事件
        EditUserModal.initEvents();
        
        // 加载部门数据
        EditUserModal.loadDepartments(userData.department);
        
        // 加载角色数据
        EditUserModal.loadRoles(userData.role);
        
        // 根据用户状态设置正确的选项
        if (userData.status === '0' || (userData.role && userData.role.includes('停用'))) {
            const disabledRadio = document.getElementById('status-disabled');
            const normalRadio = document.getElementById('status-normal');
            if (disabledRadio && normalRadio) {
                disabledRadio.checked = true;
                normalRadio.checked = false;
            }
        }
        
        // 显示模态框
        modal.classList.add('show');
    }
    
    // 初始化事件
    static initEvents() {
        const modal = document.getElementById('editUserModal');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = document.getElementById('edit-cancel-btn');
        const saveBtn = document.getElementById('edit-save-btn');
        const form = modal.querySelector('.edit-user-form');
        
        // 关闭事件
        closeBtn.addEventListener('click', EditUserModal.closeModal);
        cancelBtn.addEventListener('click', EditUserModal.closeModal);
        
        // 点击外部关闭
        modal.querySelector('.modal-overlay').addEventListener('click', EditUserModal.closeModal);
        
        // ESC键关闭
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('show')) {
                EditUserModal.closeModal();
            }
        }, { once: true });
        
        // 表单验证
        EditUserModal.initFormValidation(form);
        
        // 表单提交
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            EditUserModal.submitForm(form);
        });
        
        // 初始化角色多选组件
        EditUserModal.initCustomMultiselect();
        
        // 为状态单选框组添加键盘导航支持
        const radioGroup = modal.querySelector('.custom-radio-group');
        if (radioGroup) {
            const radioButtons = radioGroup.querySelectorAll('input[type="radio"]');
            
            // 添加键盘事件处理
            radioGroup.addEventListener('keydown', (e) => {
                const currentIndex = Array.from(radioButtons).findIndex(radio => radio === document.activeElement);
                
                if (currentIndex !== -1) {
                    // 右箭头或下箭头：选择下一个选项
                    if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
                        e.preventDefault();
                        const nextIndex = (currentIndex + 1) % radioButtons.length;
                        radioButtons[nextIndex].focus();
                        radioButtons[nextIndex].checked = true;
                    }
                    // 左箭头或上箭头：选择上一个选项
                    else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
                        e.preventDefault();
                        const prevIndex = (currentIndex - 1 + radioButtons.length) % radioButtons.length;
                        radioButtons[prevIndex].focus();
                        radioButtons[prevIndex].checked = true;
                    }
                    // 空格键：切换选中状态
                    else if (e.key === ' ') {
                        e.preventDefault();
                        radioButtons[currentIndex].checked = true;
                    }
                }
            });
            
            // 添加焦点状态样式支持
            radioButtons.forEach(radio => {
                radio.addEventListener('focus', () => {
                    radio.parentElement.classList.add('focused');
                });
                
                radio.addEventListener('blur', () => {
                    radio.parentElement.classList.remove('focused');
                });
            });
        }
    }
    
    // 加载部门数据
    static loadDepartments(selectedDepartmentName) {
        const departmentSelect = document.getElementById('edit-department');
        const errorElement = document.getElementById('edit-department-error');
        
        // 清空现有选项
        departmentSelect.innerHTML = '<option value="">加载中...</option>';
        errorElement.textContent = '';
        
        try {
            // 从组织架构管理模块获取所有组织数据
            const organizations = OrgStructureManager.getAllOrganizations();
            
            // 清空并重新构建选项
            departmentSelect.innerHTML = '<option value="">请选择部门</option>';
            
            // 按层级顺序显示组织
            const sortedOrgs = organizations.sort((a, b) => {
                if (a.parentId === b.parentId) {
                    return a.id - b.id;
                }
                return a.parentId - b.parentId;
            });
            
            // 记录选中的部门ID
            let selectedDeptId = '';
            
            // 添加选项
            sortedOrgs.forEach(org => {
                const option = document.createElement('option');
                option.value = org.id;
                
                // 根据层级添加缩进
                let indent = '';
                let currentOrg = org;
                while (currentOrg.parentId !== 0) {
                    indent += '    ';
                    currentOrg = organizations.find(o => o.id === currentOrg.parentId);
                }
                
                option.textContent = indent + org.name;
                departmentSelect.appendChild(option);
                
                // 匹配选择的部门
                if (org.name === selectedDepartmentName) {
                    selectedDeptId = org.id;
                }
            });
            
            // 设置默认选择
            if (selectedDeptId) {
                departmentSelect.value = selectedDeptId;
            }
        } catch (error) {
            console.error('加载部门数据失败:', error);
            departmentSelect.innerHTML = '<option value="">加载失败</option>';
            errorElement.textContent = '加载部门数据失败，请稍后重试';
        }
    }
    
    // 加载角色数据
    static loadRoles(selectedRoleName) {
        const multiselectOptions = document.getElementById('edit-roles-multiselect-options');
        const rolesSelect = document.getElementById('edit-roles');
        const errorElement = document.getElementById('edit-roles-error');
        
        // 清空现有选项
        multiselectOptions.innerHTML = '<div class="multiselect-option"><span>加载中...</span></div>';
        errorElement.textContent = '';
        
        try {
            // 从用户角色管理模块获取所有角色数据
            const roles = UserRoleManager.getAllRoles();
            
            // 清空并重新构建选项
            multiselectOptions.innerHTML = '';
            rolesSelect.innerHTML = '';
            
            // 按ID排序角色
            const sortedRoles = roles.sort((a, b) => a.id - b.id);
            
            // 记录当前选择的角色ID
            const selectedRoleId = roles.find(role => role.name === selectedRoleName)?.id || '';
            
            // 添加选项到自定义多选组件和隐藏的原生select
            sortedRoles.forEach(role => {
                // 自定义多选组件的选项
                const optionDiv = document.createElement('div');
                optionDiv.className = 'multiselect-option';
                
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.value = role.id;
                checkbox.id = `edit-role-${role.id}`;
                
                // 设置默认选择
                if (role.id == selectedRoleId) {
                    checkbox.checked = true;
                    optionDiv.classList.add('selected');
                }
                
                const label = document.createElement('label');
                label.htmlFor = checkbox.id;
                label.textContent = role.name;
                
                optionDiv.appendChild(checkbox);
                optionDiv.appendChild(label);
                multiselectOptions.appendChild(optionDiv);
                
                // 原生select的选项
                const option = document.createElement('option');
                option.value = role.id;
                option.textContent = role.name;
                
                // 设置默认选择
                if (role.id == selectedRoleId) {
                    option.selected = true;
                }
                
                rolesSelect.appendChild(option);
            });
            
            // 更新显示的文本
            EditUserModal.updateMultiselectDisplay();
        } catch (error) {
            console.error('加载角色数据失败:', error);
            multiselectOptions.innerHTML = '<div class="multiselect-option"><span>加载失败</span></div>';
            errorElement.textContent = '加载角色数据失败，请稍后重试';
        }
    }
    
    // 初始化自定义多选组件
    static initCustomMultiselect() {
        const multiselect = document.querySelector('#editUserModal .custom-multiselect');
        const header = document.querySelector('#edit-roles-multiselect-header');
        const dropdown = document.querySelector('#edit-roles-multiselect-dropdown');
        const searchInput = document.querySelector('#edit-roles-search-input');
        const multiselectOptions = document.querySelector('#edit-roles-multiselect-options');
        const hiddenSelect = document.querySelector('#edit-roles');
        
        // 点击头部切换下拉框
        header.addEventListener('click', () => {
            multiselect.classList.toggle('open');
        });
        
        // 选项点击事件
        multiselectOptions.addEventListener('click', (e) => {
            const optionDiv = e.target.closest('.multiselect-option');
            if (optionDiv) {
                const checkbox = optionDiv.querySelector('input[type="checkbox"]');
                if (checkbox) {
                    checkbox.checked = !checkbox.checked;
                    optionDiv.classList.toggle('selected', checkbox.checked);
                    
                    // 更新原生select元素
                    const option = hiddenSelect.querySelector(`option[value="${checkbox.value}"]`);
                    if (option) {
                        option.selected = checkbox.checked;
                    }
                    
                    // 更新显示的文本
                    EditUserModal.updateMultiselectDisplay();
                    
                    // 触发验证
                    const form = document.querySelector('#editUserModal .edit-user-form');
                    EditUserModal.validateField('edit-roles', Array.from(hiddenSelect.selectedOptions).map(opt => opt.value));
                    EditUserModal.checkFormValidity(form);
                }
            }
        });
        
        // 搜索功能
        searchInput.addEventListener('input', (e) => {
            const searchText = e.target.value.toLowerCase();
            const options = multiselectOptions.querySelectorAll('.multiselect-option');
            
            options.forEach(option => {
                const label = option.querySelector('label');
                if (label.textContent.toLowerCase().includes(searchText)) {
                    option.style.display = 'flex';
                } else {
                    option.style.display = 'none';
                }
            });
        });
        
        // 点击外部关闭下拉框
        document.addEventListener('click', (e) => {
            if (!multiselect.contains(e.target)) {
                multiselect.classList.remove('open');
            }
        }, { once: true });
    }
    
    // 更新多选组件的显示文本
    static updateMultiselectDisplay() {
        const hiddenSelect = document.querySelector('#edit-roles');
        const inputDisplay = document.querySelector('#editUserModal .multiselect-input');
        const selectedOptions = Array.from(hiddenSelect.selectedOptions);
        
        if (selectedOptions.length === 0) {
            inputDisplay.placeholder = '选择角色';
            inputDisplay.value = '';
        } else if (selectedOptions.length === 1) {
            inputDisplay.value = selectedOptions[0].textContent;
        } else {
            inputDisplay.value = `${selectedOptions.length}个角色已选择`;
        }
    }
    
    // 表单验证初始化
    static initFormValidation(form) {
        // 用户名称验证
        const usernameInput = document.querySelector('#edit-username');
        usernameInput.addEventListener('input', () => {
            EditUserModal.validateField('edit-username', usernameInput.value);
            EditUserModal.checkFormValidity(form);
        });
        
        // 手机号验证
        const phoneInput = document.querySelector('#edit-phone');
        phoneInput.addEventListener('input', () => {
            EditUserModal.validateField('edit-phone', phoneInput.value);
            EditUserModal.checkFormValidity(form);
        });
        
        // 部门验证
        const departmentSelect = document.querySelector('#edit-department');
        departmentSelect.addEventListener('change', () => {
            EditUserModal.validateField('edit-department', departmentSelect.value);
            EditUserModal.checkFormValidity(form);
        });
        
        // 角色验证
        const rolesSelect = document.querySelector('#edit-roles');
        rolesSelect.addEventListener('change', () => {
            EditUserModal.validateField('edit-roles', Array.from(rolesSelect.selectedOptions).map(opt => opt.value));
            EditUserModal.checkFormValidity(form);
        });
        
        // 初始验证
        EditUserModal.validateField('edit-username', usernameInput.value);
        EditUserModal.validateField('edit-phone', phoneInput.value);
        EditUserModal.validateField('edit-department', departmentSelect.value);
        EditUserModal.validateField('edit-roles', Array.from(rolesSelect.selectedOptions).map(opt => opt.value));
        EditUserModal.checkFormValidity(form);
    }
    
    // 验证字段
    static validateField(fieldId, value) {
        let isValid = true;
        let errorMessage = '';
        const errorElement = document.querySelector(`#${fieldId}-error`);
        const inputElement = document.querySelector(`#${fieldId}`);
        
        switch (fieldId) {
            case 'edit-username':
                if (!value.trim()) {
                    errorMessage = '请输入用户名称';
                    isValid = false;
                } else if (value.length < 2 || value.length > 10) {
                    errorMessage = '用户名称必须为2-10个字符';
                    isValid = false;
                }
                break;
            
            case 'edit-phone':
                const phoneRegex = /^1[3-9]\d{9}$/;
                if (!value.trim()) {
                    errorMessage = '请输入手机号码';
                    isValid = false;
                } else if (!phoneRegex.test(value)) {
                    errorMessage = '请输入有效的手机号码';
                    isValid = false;
                }
                break;
            
            case 'edit-department':
                if (!value) {
                    errorMessage = '请选择部门';
                    isValid = false;
                }
                break;
            
            case 'edit-roles':
                if (value.length === 0) {
                    errorMessage = '请至少选择一个角色';
                    isValid = false;
                }
                break;
        }
        
        errorElement.textContent = errorMessage;
        
        if (isValid) {
            inputElement.classList.remove('is-invalid');
            inputElement.classList.add('is-valid');
        } else {
            inputElement.classList.remove('is-valid');
            inputElement.classList.add('is-invalid');
        }
        
        return isValid;
    }
    
    // 检查表单整体有效性
    static checkFormValidity(form) {
        const saveBtn = document.querySelector('#edit-save-btn');
        const usernameValid = EditUserModal.validateField('edit-username', document.querySelector('#edit-username').value);
        const phoneValid = EditUserModal.validateField('edit-phone', document.querySelector('#edit-phone').value);
        const departmentValid = EditUserModal.validateField('edit-department', document.querySelector('#edit-department').value);
        const rolesValid = EditUserModal.validateField('edit-roles', Array.from(document.querySelector('#edit-roles').selectedOptions).map(opt => opt.value));
        
        saveBtn.disabled = !(usernameValid && phoneValid && departmentValid && rolesValid);
    }
    
    // 提交表单
    static submitForm(form) {
        const saveBtn = document.querySelector('#edit-save-btn');
        const userId = document.querySelector('#edit-user-id').value;
        const username = document.querySelector('#edit-username').value;
        const phone = document.querySelector('#edit-phone').value;
        const department = document.querySelector('#edit-department').value;
        const roles = Array.from(document.querySelector('#edit-roles').selectedOptions).map(opt => opt.value);
        // 获取用户状态值
        const status = document.querySelector('input[name="status"]:checked').value;
        
        // 显示保存状态
        const originalBtnText = saveBtn.innerHTML;
        saveBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 保存中...';
        saveBtn.disabled = true;
        
        // 模拟API请求
        setTimeout(() => {
            try {
                // 这里可以添加实际的API请求逻辑
                console.log('修改用户:', { userId, username, phone, department, roles, status });
                
                // 获取部门和角色名称
                const departmentName = document.querySelector(`#edit-department option[value="${department}"]`).textContent.trim();
                let roleName = '';
                if (roles.length === 1) {
                    roleName = document.querySelector(`#edit-roles option[value="${roles[0]}"]`).textContent.trim();
                } else {
                    roleName = `${roles.length}个角色`;
                }
                
                // 更新表格中的用户数据
                const container = document.querySelector('.content-container'); // 假设这是包含表格的容器
                if (container) {
                    const rows = container.querySelectorAll('.table-container tbody tr');
                    rows.forEach(row => {
                        if (row.rowIndex === parseInt(userId)) {
                            row.cells[2].textContent = username;  // 更新用户名称
                            row.cells[3].textContent = departmentName;  // 更新部门
                            row.cells[4].textContent = roleName;  // 更新角色
                            row.cells[5].textContent = phone;  // 更新手机号
                            // 更新用户状态显示
                            if (row.cells.length > 6) {
                                const statusBtn = row.cells[6].querySelector('.status-btn');
                                if (statusBtn) {
                                    statusBtn.textContent = status === '1' ? '启用' : '停用';
                                    statusBtn.className = 'status-btn ' + (status === '1' ? 'active' : 'inactive');
                                }
                            }
                        }
                    });
                }
                
                // 保存成功后关闭模态框
                EditUserModal.closeModal();
                
                alert('用户修改成功！');
            } catch (error) {
                console.error('修改用户失败:', error);
                alert('修改用户失败，请稍后重试');
                saveBtn.innerHTML = originalBtnText;
                saveBtn.disabled = false;
            }
        }, 1500);
    }
    
    // 关闭模态框
    static closeModal() {
        const modal = document.getElementById('editUserModal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => {
                modal.remove();
            }, 300);
        }
    }

    // 绑定事件
    static bindEvents() {
        // 事件绑定已在initEvents中实现
        console.log('EditUserModal: 事件绑定已完成');
    }

    // 验证表单
    static validateForm(form) {
        const nameInput = form.querySelector('#userName');
        const phoneInput = form.querySelector('#userPhone');
        const deptSelect = form.querySelector('#deptId');
        const roleSelect = form.querySelector('#roles');

        // 姓名验证
        if (!nameInput.value.trim()) {
            this.showError(nameInput, '请输入用户名');
            return false;
        } else {
            this.hideError(nameInput);
        }

        // 手机号验证
        if (!phoneInput.value.trim() || !/^1[3-9]\d{9}$/.test(phoneInput.value)) {
            this.showError(phoneInput, '请输入正确的手机号');
            return false;
        } else {
            this.hideError(phoneInput);
        }

        // 部门验证
        if (!deptSelect.value) {
            this.showError(deptSelect, '请选择部门');
            return false;
        } else {
            this.hideError(deptSelect);
        }

        // 角色验证
        const selectedRoles = Array.from(roleSelect.selectedOptions).map(option => option.value);
        if (selectedRoles.length === 0) {
            this.showError(roleSelect, '请至少选择一个角色');
            return false;
        } else {
            this.hideError(roleSelect);
        }

        return true;
    }

    // 设置表单数据
    static setFormData(form, user) {
        if (!form || !user) return;

        form.querySelector('#userId').value = user.userId || '';
        form.querySelector('#userAccount').value = user.userAccount || '';
        form.querySelector('#userName').value = user.userName || '';
        form.querySelector('#userPhone').value = user.userPhone || '';
        form.querySelector('#userEmail').value = user.userEmail || '';
        form.querySelector('#deptId').value = user.deptId || '';
        form.querySelector('#orgName').value = user.orgName || '';
        form.querySelector('#jobPosition').value = user.jobPosition || '';
        form.querySelector('#joinDate').value = user.joinDate || '';

        // 设置角色选择
        const roleSelect = form.querySelector('#roles');
        Array.from(roleSelect.options).forEach(option => {
            option.selected = user.roles && user.roles.includes(option.value);
        });

        // 设置用户状态
        const statusSelect = form.querySelector('#status');
        if (statusSelect) {
            statusSelect.value = user.status || '1'; // 默认正常
        }
    }

    // 显示错误信息
    static showError(input, message) {
        const errorId = input.id + '-error';
        const errorElement = document.getElementById(errorId);
        if (errorElement) {
            errorElement.textContent = message;
            errorElement.style.display = 'block';
        }
        input.classList.add('is-invalid');
    }

    // 隐藏错误信息
    static hideError(input) {
        const errorId = input.id + '-error';
        const errorElement = document.getElementById(errorId);
        if (errorElement) {
            errorElement.style.display = 'none';
        }
        input.classList.remove('is-invalid');
    }


}

// 批量导入模态框实现
class BatchImportModal {
    static importHistory = [
        { id: 1, time: '2024-01-15 10:30:45', account: 'admin', fileName: '用户批量导入.xlsx', total: 50, success: 48, fail: 2 },
        { id: 2, time: '2024-01-10 14:20:30', account: 'admin', fileName: '新员工名单.xlsx', total: 30, success: 30, fail: 0 },
        { id: 3, time: '2024-01-05 09:15:20', account: 'hr001', fileName: '学员信息.xlsx', total: 100, success: 95, fail: 5 }
    ];

    static showModal() {
        // 创建模态框元素
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.id = 'batchImportModal';

        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content" style="max-width: 900px;">
                <div class="modal-header">
                    <h3>批量导入用户</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <div class="batch-import-container">
                    <!-- 导入区域 -->
                    <div class="import-section">
                        <h4><i class="fas fa-upload"></i> 导入文件</h4>
                        <div class="import-area">
                            <div class="upload-box" id="upload-box">
                                <i class="fas fa-cloud-upload-alt"></i>
                                <p>点击选择文件或拖拽文件到此处</p>
                                <p class="hint">支持格式：.xlsx, .xls（最大10MB）</p>
                                <input type="file" id="file-input" accept=".xlsx,.xls" style="display: none;">
                            </div>
                            <div class="file-info" id="file-info" style="display: none;">
                                <div class="file-details">
                                    <i class="fas fa-file-excel"></i>
                                    <span class="file-name" id="file-name"></span>
                                    <span class="file-size" id="file-size"></span>
                                </div>
                                <button class="btn-remove-file" id="remove-file-btn">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <div class="import-actions">
                                <button class="btn btn-download-template">
                                    <i class="fas fa-download"></i> 下载导入模板
                                </button>
                                <button class="btn btn-primary" id="start-import-btn" disabled>
                                    <i class="fas fa-upload"></i> 开始导入
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- 导入历史区域 -->
                    <div class="history-section">
                        <h4><i class="fas fa-history"></i> 导入历史</h4>
                        <div class="history-table-container">
                            <table class="history-table">
                                <thead>
                                    <tr>
                                        <th>导入时间</th>
                                        <th>导入人账号</th>
                                        <th>文件名</th>
                                        <th>总数</th>
                                        <th>成功</th>
                                        <th>失败</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="history-tbody">
                                    <!-- 动态加载历史记录 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        `;

        // 添加到文档
        document.body.appendChild(modal);

        // 初始化事件
        BatchImportModal.initEvents();

        // 加载导入历史
        BatchImportModal.loadHistory();

        // 显示模态框
        modal.classList.add('show');
    }

    static initEvents() {
        const modal = document.getElementById('batchImportModal');
        const closeBtn = modal.querySelector('.modal-close-btn');
        const uploadBox = document.getElementById('upload-box');
        const fileInput = document.getElementById('file-input');
        const removeFileBtn = document.getElementById('remove-file-btn');
        const startImportBtn = document.getElementById('start-import-btn');
        const downloadTemplateBtn = modal.querySelector('.btn-download-template');

        // 关闭事件
        closeBtn.addEventListener('click', BatchImportModal.closeModal);
        modal.querySelector('.modal-overlay').addEventListener('click', BatchImportModal.closeModal);

        // ESC键关闭
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('show')) {
                BatchImportModal.closeModal();
            }
        });

        // 点击上传区域触发文件选择
        uploadBox.addEventListener('click', () => {
            fileInput.click();
        });

        // 文件选择事件
        fileInput.addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (file) {
                BatchImportModal.handleFileSelect(file);
            }
        });

        // 拖拽上传
        uploadBox.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadBox.classList.add('drag-over');
        });

        uploadBox.addEventListener('dragleave', () => {
            uploadBox.classList.remove('drag-over');
        });

        uploadBox.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadBox.classList.remove('drag-over');
            const file = e.dataTransfer.files[0];
            if (file) {
                BatchImportModal.handleFileSelect(file);
            }
        });

        // 移除文件
        removeFileBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            BatchImportModal.removeFile();
        });

        // 开始导入
        startImportBtn.addEventListener('click', () => {
            BatchImportModal.startImport();
        });

        // 下载模板
        downloadTemplateBtn.addEventListener('click', () => {
            BatchImportModal.downloadTemplate();
        });
    }

    static handleFileSelect(file) {
        // 验证文件类型
        const validTypes = ['.xlsx', '.xls'];
        const fileExt = '.' + file.name.split('.').pop().toLowerCase();
        if (!validTypes.includes(fileExt)) {
            alert('只支持 .xlsx 或 .xls 格式的文件');
            return;
        }

        // 验证文件大小（10MB）
        const maxSize = 10 * 1024 * 1024;
        if (file.size > maxSize) {
            alert('文件大小不能超过 10MB');
            return;
        }

        // 显示文件信息
        document.getElementById('file-name').textContent = file.name;
        document.getElementById('file-size').textContent = BatchImportModal.formatFileSize(file.size);
        document.getElementById('upload-box').style.display = 'none';
        document.getElementById('file-info').style.display = 'flex';
        document.getElementById('start-import-btn').disabled = false;

        // 保存文件引用
        BatchImportModal.selectedFile = file;
    }

    static removeFile() {
        document.getElementById('upload-box').style.display = 'flex';
        document.getElementById('file-info').style.display = 'none';
        document.getElementById('start-import-btn').disabled = true;
        document.getElementById('file-input').value = '';
        BatchImportModal.selectedFile = null;
    }

    static formatFileSize(bytes) {
        if (bytes < 1024) return bytes + ' B';
        if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
    }

    static startImport() {
        if (!BatchImportModal.selectedFile) {
            alert('请先选择要导入的文件');
            return;
        }

        const startImportBtn = document.getElementById('start-import-btn');
        const originalText = startImportBtn.innerHTML;

        // 显示加载状态
        startImportBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 导入中...';
        startImportBtn.disabled = true;

        // 模拟导入过程
        setTimeout(() => {
            // 模拟导入结果
            const totalCount = Math.floor(Math.random() * 50) + 20;
            const successCount = totalCount - Math.floor(Math.random() * 5);
            const failCount = totalCount - successCount;

            // 添加导入记录到历史
            const newRecord = {
                id: BatchImportModal.importHistory.length + 1,
                time: new Date().toLocaleString('zh-CN', {
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit',
                    hour12: false
                }).replace(/\//g, '-'),
                account: 'admin', // 实际应从登录用户获取
                fileName: BatchImportModal.selectedFile.name,
                total: totalCount,
                success: successCount,
                fail: failCount
            };

            BatchImportModal.importHistory.unshift(newRecord);
            BatchImportModal.loadHistory();

            // 恢复按钮状态
            startImportBtn.innerHTML = originalText;
            startImportBtn.disabled = false;

            // 清除已选文件
            BatchImportModal.removeFile();

            // 显示结果
            alert(`导入完成！\n总数：${totalCount}\n成功：${successCount}\n失败：${failCount}`);

            // 如果有失败记录，提示下载失败详情
            if (failCount > 0) {
                BatchImportModal.showDownloadConfirm();
            }
        }, 2000);
    }

    static loadHistory() {
        const tbody = document.getElementById('history-tbody');
        tbody.innerHTML = '';

        if (BatchImportModal.importHistory.length === 0) {
            tbody.innerHTML = '<tr><td colspan="7" style="text-align: center; color: #999;">暂无导入历史</td></tr>';
            return;
        }

        BatchImportModal.importHistory.forEach(record => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${record.time}</td>
                <td>${record.account}</td>
                <td title="${record.fileName}">${record.fileName.length > 20 ? record.fileName.substring(0, 20) + '...' : record.fileName}</td>
                <td>${record.total}</td>
                <td style="color: #28a745;">${record.success}</td>
                <td style="color: ${record.fail > 0 ? '#dc3545' : '#666'};">${record.fail}</td>
                <td>
                    ${record.fail > 0 ? '<a href="#" class="download-failed-link"><i class="fas fa-download"></i> 失败详情</a>' : '<span style="color: #999;">-</span>'}
                </td>
            `;

            // 添加下载失败详情事件
            if (record.fail > 0) {
                const downloadLink = row.querySelector('.download-failed-link');
                downloadLink.addEventListener('click', (e) => {
                    e.preventDefault();
                    BatchImportModal.downloadFailedRecords(record.id);
                });
            }

            tbody.appendChild(row);
        });
    }

    static downloadTemplate() {
        // 模拟下载模板
        alert('正在下载导入模板...\n\n模板包含以下列：\n- 账号（必填）\n- 用户名称（必填）\n- 手机号（必填）\n- 部门（必填）\n- 角色（必填）\n- 用户状态（必填，正常/停用）\n- 密码（必填）');

        // 实际项目中应该触发真实的文件下载
        console.log('下载用户导入模板');
    }

    static downloadFailedRecords(recordId) {
        // 模拟下载失败记录
        alert('正在下载失败详情...\n\n失败记录将包含：\n- 失败原因\n- 原始数据\n- 建议修改方案');

        // 实际项目中应该触发真实的文件下载
        console.log('下载失败记录，记录ID:', recordId);
    }

    static showDownloadConfirm() {
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content" style="max-width: 400px;">
                <div class="modal-header">
                    <h3>下载确认</h3>
                    <button class="modal-close-btn"><i class="fas fa-times"></i></button>
                </div>
                <div style="padding: 20px; font-size: 16px; color: #333;">
                    有部分数据导入失败，是否下载失败详情？
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" id="download-cancel-btn">取消</button>
                    <button type="button" class="btn btn-primary" id="download-confirm-btn">确认下载</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        const closeBtn = modal.querySelector('.modal-close-btn');
        const cancelBtn = modal.querySelector('#download-cancel-btn');
        const confirmBtn = modal.querySelector('#download-confirm-btn');
        const overlay = modal.querySelector('.modal-overlay');

        const closeModal = () => {
            modal.classList.remove('show');
            setTimeout(() => modal.remove(), 300);
        };

        closeBtn.addEventListener('click', closeModal);
        cancelBtn.addEventListener('click', closeModal);
        overlay.addEventListener('click', closeModal);
        confirmBtn.addEventListener('click', () => {
            BatchImportModal.downloadFailedRecords();
            closeModal();
        });

        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') closeModal();
        });

        setTimeout(() => modal.classList.add('show'), 10);
    }

    static closeModal() {
        const modal = document.getElementById('batchImportModal');
        if (modal) {
            modal.classList.remove('show');
            setTimeout(() => {
                modal.remove();
            }, 300);
        }
    }
}
